#pragma once

#include "util.hpp"
#include <iostream>
#include <vector>
#include <functional>
#include <cstdio>
#include <unistd.h>

using namespace std;

using func = function<void()>;

//do while宏封装代码块
#define INIT(cbs)\
    do\
        {\
            cbs.push_back(printlog);\
            cbs.push_back(download);\
            cbs.push_back(execsql);\
        } while(0)

#define EXEC_OTHER(cbs)\
    do\
    {\
        for (auto& cb : cbs)\
            cb();\
    } while(0)

int main()
{
    setNonBlock(0);
    vector<func> cbs;
    INIT(cbs);
    EXEC_OTHER(cbs);
    while (true)
    {
        // printf("#Enter: ");
        // fflush(stdout);
        char buffer[1024];
        //非阻塞式读取 如果当前没读到数据直接返回值 处理其他业务 下次循环再次读取
        int n = read(0, buffer, sizeof buffer - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "#Echo: " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read end" << endl;
            break;
        }
        else
        {
            if (errno == EAGAIN)//输入缓冲区资源未就绪
            {
                cout << "resource not prepared" << endl;
                EXEC_OTHER(cbs);
            }
            else if (errno == EINTR)//读取过程被信号中断
            {
                continue;
            }
            else
            {
                cout << "error: " << strerror(errno) << endl;
                break;
            }
        }
        sleep(1);
    }
    return 0;
}